import { connect } from 'dva';
import React, { Component, Fragment} from 'react';
import { Modal, Button, Form, Input, Row, Col, message } from 'antd'
import Timer from './Components/Timer'
import styles from './index.less';

const layout = { labelCol: { span: 3 }, wrapperCol: { span: 7 } }
const tailLayout = { wrapperCol: { offset: 5, span: 16 } }

@connect( ({infoaccount}) => ({accountInfo: infoaccount.accountInfo}))
class Account extends Component {
    constructor(props){
        super(props)
        this.state = {
            showCellPhone: false,
            isStepOne: true,
        }
    }
    // 修改手机号 确认
    modifyCellPhone = ()=>{
        this.setState({
            showCellPhone: true
        })
    }
    // 修改手机号 取消
    phoneCancel = ()=>{
        this.setState({
            showCellPhone: false, 
            isStepOne: true    
        },()=>{
            this.requestInfo()
        })   
    }
    // 修改手机号 下一步
    nextStep = (data)=>{
        if(data === false){
            this.setState({
                isStepOne: false
            })        
        }
    }
    // 获取账号信息
    requestInfo(){
        const { dispatch } = this.props
        dispatch({
            type: 'infoaccount/fetchInfo',
            payload: {
              data: { channel: 5, username: 'test01' }
            }
        })
    }
    componentDidMount(){
       this.requestInfo()
    }
  
    render() {
        const { isStepOne } = this.state        
        return (
            <div className={styles.accountBox}>
                <InfoCom 
                    showModifyMobile={this.modifyCellPhone}
                />
                <Modal 
                    visible={ this.state.showCellPhone } 
                    onCancel={()=>{ this.setState({ showCellPhone: false })}} 
                    title={this.state.isStepOne ? '验证手机号': '填写新手机号'} 
                    footer=''
                    width={380}
                    className={styles.account_modal}
                >
                    { isStepOne ?  
                        <StepOneCom 
                            nextStep={this.nextStep}
                        /> : 
                        <StepTwoCom 
                            phoneCancel={this.phoneCancel}
                        />
                    }                                   
                </Modal>
            </div>
        )
    }
}
export default Account;

/**
 * 账户信息 展示 编辑
 */
@Form.create()
@connect( ({infoaccount}) => ({
    accountInfo: infoaccount.accountInfo,
    isEdit: infoaccount.isEdit
}))
class InfoCom extends Component{
    handleSubmit = e => {
        e.preventDefault();   
        this.props.form.validateFields((err, values) => {
            if (!err) {
                const { dispatch,  accountInfo: {username} } = this.props
                // updator is current user
                const { mail, name } = values
                const params = { 
                    updator: username, // 当前登录用户
                    userName: username,
                    mail,
                    name, 
                    channel: 5 
                }

                dispatch({
                    type: 'infoaccount/modfiyInfo',
                    payload: {
                        data: params
                    }
                }).then(()=>{                  
                    dispatch({
                        type: 'infoaccount/fetchInfo',
                        payload: {
                          data: { channel: 5, username: 'test01' }
                        }
                    }).then(()=>{
                        this._toggleCancel()
                    })    
                    message.success("修改成功")                 
                })
            }
        })
    }
    cancelEdit = ()=>{
        this._toggleCancel()
    }
    showEidtContent = ()=>{
        this._toggleCancel()
    }
    showPhoneContent = ()=>{
        this.props.showModifyMobile()
    }
    _toggleCancel = ()=>{
        const { dispatch } = this.props
        dispatch({
            type: 'infoaccount/toggleEdit',
            payload: null
        })
    }
    render(){
        const formItemLayout = {
            labelCol: {
              xs: { span: 24 },
              sm: { span: 6 },
            },
            wrapperCol: {
              xs: { span: 24 },
              sm: { span: 14 },
            },
        };
        const serviceArr = [
            {code: 1, name: '揽收'},
            {code: 2, name: '出港操作'},
            {code: 3, name: '空运'},
            {code: 4, name: '提货'},
            {code: 5, name: '派送'}
        ]
        const { form, accountInfo= {}, isEdit } = this.props;
        const attributeTag = accountInfo && accountInfo.attributeTag && ((accountInfo.attributeTag.includes("1") ? "专属供应商" : '') + ' ' + 
        (accountInfo.attributeTag && accountInfo.attributeTag.includes("2") ? "自营店供应商" : '') + ' ' + 
        (accountInfo.attributeTag && accountInfo.attributeTag.includes("3") ? "平台供应商" : ''))

    
        const serviceData = accountInfo && accountInfo.serviceType && accountInfo.serviceType.split(',')
        console.log(serviceData)
        let serviceName = ''
        if(serviceData){
           
            serviceData.forEach(item => {
                serviceArr.forEach(i=>{
                    if(i.code == item){
                        serviceName += i.name + ' '
                    }
                })
            })
        }
        console.log('serviceName', serviceName)
        return (
            <div>
                <Row style={{height: '50px', textAlign: 'right'}}>
                    { isEdit ? null : <Button type="primary" onClick={this.showEidtContent}>编辑</Button>} 
                </Row>              
                <Form 
                    {...formItemLayout} 
                    onSubmit={this.handleSubmit} 
                    hideRequiredMark={true}
                    style={{padding: '20px 100px',boxSizing: 'border-box'}}
                >
                    <Row>
                        <Col span={12}>
                            <Form.Item label="名称">
                                { isEdit ? form.getFieldDecorator('name', {
                                        rules: [
                                            { required: true, message: '请填写名称' },
                                            { max: 30,  message: '名称不得超过30字符' },
                                            { pattern:  /^[\u4e00-\u9fa5_a-zA-Z0-9-]+$/,
                                                message: '只能输入中英文、数字和符号“-”、“_”'}
                                        ],
                                        initialValue: accountInfo.name,
                                    })(
                                        <Input disabled={accountInfo.accountType == 1} maxLength={30}/>
                                    ) : accountInfo.name
                                }
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="账号">
                                { isEdit ? form.getFieldDecorator('username', {
                                        initialValue: accountInfo.username,
                                    })( <Input disabled/> ) : accountInfo.username 
                                }
                            </Form.Item>                  
                        </Col>
                    </Row>                  
                    <Row>
                        <Col span={12}>
                            <Form.Item label="手机">
                                { isEdit ? form.getFieldDecorator('mobile', {
                                        initialValue: accountInfo.mobile,
                                    })( <Input disabled/>) : (<div>{accountInfo.mobile} <a style={{marginLeft: '10px'}} onClick={this.showPhoneContent}>更换手机号</a></div>)
                                }
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="邮箱">
                                { isEdit ? form.getFieldDecorator('mail', {
                                        rules: [
                                            { required: true, message: '请填写邮箱地址' },
                                            {
                                                pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,                                              
                                                message: '邮箱格式不正确',
                                            },                                             
                                            { max: 50,  message: '邮箱不得超过50字符' },
                                        ],
                                        initialValue: accountInfo.mail,
                                    })( <Input maxLength={50}/> ) : accountInfo.mail
                                }
                            </Form.Item>                  
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <Form.Item label="账号类型">
                                { isEdit ? form.getFieldDecorator('accountType', {
                                       initialValue: accountInfo.accountType==1?'主账户':'子账户'
                                    })( <Input disabled/> ) : (accountInfo.accountType==1?'主账户':'子账户')
                                }
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="服务城市">
                                { isEdit ? form.getFieldDecorator('city', {
                                        initialValue: accountInfo.city
                                    })( <Input disabled/> ) : accountInfo.city
                                }
                            </Form.Item>                  
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <Form.Item label="服务类型">
                                { isEdit ? form.getFieldDecorator('serviceType', {
                                        initialValue: serviceName
                                    })( <Input disabled/> ) : serviceName
                                }
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="供应商属性">
                                { isEdit ? form.getFieldDecorator('attributeTag', {
                                         initialValue: attributeTag
                                    })( <Input disabled/> ) : attributeTag
                                }
                            </Form.Item>
                        </Col>
                    </Row>    
                    <Row>
                        <Col span={12}>
                            <Form.Item label="备注">
                                { isEdit ? form.getFieldDecorator('remark', {
                                        initialValue: accountInfo.remark
                                    })( <Input disabled/> ) : accountInfo.remark
                                }
                            </Form.Item>
                        </Col>
                    </Row>
                    {
                        isEdit ? 
                        <Row style={{display: 'flex', justifyContent: 'center', marginTop: '28px'}}>
                            <Form.Item style={{marginRight: '20px'}}>
                                <Button onClick={this.cancelEdit}>
                                    取消
                                </Button>
                            </Form.Item>         
                            <Form.Item>
                                <Button type="primary" htmlType="submit">
                                    保存
                                </Button>
                            </Form.Item>         
                        </Row> : null
                    }
                </Form>
            </div>
        )
    }
}

/**
 * 手机号码修改 步骤一
 */
@Form.create()
@connect( ({infoaccount}) => ({accountInfo: infoaccount.accountInfo}))
class StepOneCom extends Component{ 
    state = {
        validateId: null
    } 
    // 发送短信
    sendMes = ()=>{
        const { dispatch, accountInfo } = this.props
        dispatch({
            type: 'infoaccount/sendMes',
            payload: {
                data: {
                    channel: '01',
                    mobile: accountInfo.mobile,
                    username: accountInfo.username
                }
            }
        }).then((res)=>{
            console.log('send code', res)
            this.setState({
                validateId: res.data.validateId
            })
        })
    }

    // 校验验证码
    validateCode = (values)=>{
        const { dispatch } = this.props
        dispatch({
            type: 'infoaccount/validateCode',
            payload: {
                data: {
                    mode: 'REGISTRATION',
                    mobile: this.props.accountInfo.mobile,
                    code: values.captcha,
                    validateId: this.state.validateId
                } 
            }
        }).then((res)=>{
            if(res.code === 500){
                message.warning('验证码不正确，请重新输入')
                // message.warning(res.mes)
                
            }else{
                this.props.nextStep(false)
            }         
        })
    }
    // 校验并下一步
    handleSubmit = (e)=>{
        e.preventDefault()
        // this.props.nextStep(false)
        // return
        const { form } = this.props
       
        form.validateFields((errors, values) => {
            console.log('values....', values)
            if(!errors){
                if(!this.state.validateId){
                    message.warning('请先发送手机验证码')
                }else{
                    this.validateCode(values)  
                }
            }       
        })
    }
   
    // 自定义校验
    // checkCode = (rule, value, callback)=>{
    //     console.log('checkcode ......')
    //     const { dispatch } = this.props
    //     console.log('checkcode ......', dispatch)
    //     dispatch({
    //         type: 'infoaccount/validateCode',
    //         payload: {
    //             data: {
    //                 mode: 'REGISTRATION',
    //                 mobile: this.props.accountInfo.mobile,
    //                 code: values.captcha,
    //                 validateId: this.state.validateId
    //             } 
    //         } 
    //     }).then((res)=>{
    //         if(res.code === 500){
    //             callback("验证码不正确")
    //         }else{
    //             callback()
    //         }  
    //     })
    //     // if(value.length != 0){
    //     //     if(value.length<5){
    //     //         callback("aaaa")
    //     //     }else{
    //     //         callback()
    //     //     }
    //     // }else{
    //     //     callback()
    //     // }
    // }
    render(){
        const { accountInfo: {mobile}, form } = this.props
        return (
            <>
                <Form 
                    name="step_one"
                    layout="vertical"
                    onSubmit={this.handleSubmit}
                    hideRequiredMark={true}
                >
                    <Form.Item label="原手机号">
                        { form.getFieldDecorator('mobile', { initialValue: mobile })( <Input disabled size="large"/>) }
                    </Form.Item>
                    <Row gutter={8}>
                        <Col span={15}>
                            <Form.Item label="验证码">
                                {/* { form.getFieldDecorator('captcha', { 
                                        rules: [{ required: true, message: '请填写验证码' },
                                        {validator: this.checkCode}
                                    ],
                                    validateTrigger: 'onSubmit'
                                    })( <Input size="large"/>) }  */}
                                { form.getFieldDecorator('captcha', { rules: [{ required: true, message: '请填写验证码' }]
                                    })( <Input size="large" placeholder="输入短信验证码" maxLength={6}/>) } 
                            </Form.Item>
                        </Col>
                        <Col span={9} style={{marginTop: '29px'}}>
                            <Timer style={{marginLeft: '5px', width: '100%'}} canClickFromF={false} sendMes={this.sendMes}/>
                        </Col>                      
                    </Row>                     
                    <Form.Item style={{textAlign: 'right',marginTop: '20px'}}>
                        <Button disabled={!this.state.validateId} htmlType="submit" type="primary" style={{width: '120px'}} size="large">下一步</Button>
                    </Form.Item>
                </Form>
            </>
        )
    }
}

/**
 * 手机号码修改 步骤二
 */
@Form.create()
@connect( ({infoaccount}) => ({accountInfo: infoaccount.accountInfo}))
class StepTwoCom extends Component{
    state = {
        canClickFromF: true,
        mobile: '',
        validateId: ''
    }
    // 发送短信
    sendMes = ()=>{
        const { dispatch, accountInfo } = this.props
        dispatch({
            type: 'infoaccount/sendMes',
            payload: {
                data: {
                    channel: '01',
                    mobile: this.state.mobile,
                    username: accountInfo.username
                }
            }
        }).then((res)=>{
            this.setState({
                validateId: res.data.validateId
            })
        })
    }

    // 验证手机号是否正确
    handleChange = (e)=>{
        if(/^1[3|4|5|7|8][0-9]{9}$/.test(e.target.value)){
            this.setState({
                canClickFromF: false,
                mobile: e.target.value
            })
        }else{
            this.setState({
                canClickFromF: true
            })
        }
    }

    // 校验 更换
    handleSubmit = (e) => {
        e.preventDefault()     
        const { form } = this.props
        form.validateFields((errors, values) => {
            console.log('values....', values)
            if(!errors){
                if(!this.state.validateId){
                    message.warning('请先发送手机验证码')
                }else{
                    this.modifyPhone(values) 
                }        
            }                 
        })
    }

    // 更换手机号
    modifyPhone = (values)=>{
        const { dispatch } = this.props
        dispatch({
            type: 'infoaccount/modifyMobile',
            payload: {
                data: {
                    channel: 5,
                    mode: 'REGISTRATION',
                    code: values.captcha,
                    mobile: values.mobile,
                    validateId: this.state.validateId,
                    id: this.props.accountInfo.id
                }
            }
        }).then((res)=>{
            if(res.code === 500){
                message.warning("验证码不正确，请重新输入")
                 // message.warning(res.mes)  
            }else if(res.code === 1001022){
                message.warning("验证码不正确，请重新输入")    
                // message.warning(res.mes)            
            }else{
                this.props.phoneCancel()
                message.success("修改成功")
            }  
        })
    }

    render(){       
        const { form } = this.props
        return (
            <Fragment>
                <div style={{display: 'flex'}}>
                    <span style={{fontWeight: '700',fontSize: '14px', marginBottom: '10px'}}>完成以下三步操作，即可更改成功。更改后登录密码不变，原有的订单都会保留</span>
                </div>
                <Form 
                    onSubmit={this.handleSubmit}
                    layout="vertical"
                    hideRequiredMark={true}
                >   
                    <Form.Item label="第一步：填写新的手机号码">   
                        { form.getFieldDecorator('mobile', { 
                                rules: [{ required: true, message: '请填写新手机号码' }], 
                            })( <Input size="large" placeholder="输入新手机号码" maxLength={50} onChange={this.handleChange}/>) 
                        }                     
                    </Form.Item>
                    <Form.Item label="第二步：获取手机短信验证码">
                        <div style={{width: '150px',fontSize: '12px'}}>
                            <Timer canClickFromF={this.state.canClickFromF} sendMes={this.sendMes}/>
                        </div>       
                    </Form.Item>
                    <Form.Item label="第三步：填写短信验证码">
                        { form.getFieldDecorator('captcha', { 
                                rules: [{ required: true, message: '请填写验证码' }], 
                            })( <Input size="large" placeholder="输入短信验证码" maxLength={6}/>) 
                        }  
                    </Form.Item>
                    <Form.Item style={{marginTop: '30px',textAlign: 'right'}}>
                        <Button onClick={this.props.phoneCancel}>取消</Button>
                        <Button disabled={!this.state.validateId} htmlType="submit" type="primary" style={{marginLeft: '15px'}}>确认</Button>
                    </Form.Item>
                </Form>
            </Fragment>
        )
    }
}
